#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"
using namespace zyb_rpc;
using namespace std;
// using ConnectionCallback = std::function<void(const BaseConnection::ptr &)>;
// using CloseCallback = std::function<void(const BaseConnection::ptr &)>;
// using MessageCallback = std::function<void(const BaseConnection::ptr &, BaseMessage::ptr &)>;
void onRpcRequest(const BaseConnection::ptr &conn, RpcRequest::ptr &msg)
{
    cout << "收到rpc请求：" << msg->method() << endl;
    std::string body = msg->serialize();
    cout << body << endl;
    auto rpc_rsp = MessageFactory::create<RpcResponse>();
    rpc_rsp->setId("111");
    rpc_rsp->setMType(MType::RSP_RPC);
    rpc_rsp->setRCode(RCode::RCODE_OK);
    rpc_rsp->setResult(33);
    conn->send(rpc_rsp);
}

void onTopicRequest(const BaseConnection::ptr &conn, TopicRequest::ptr &msg)
{
    cout << "收到rpc请求：" << msg->topicKey();
    std::string body = msg->serialize();
    cout << body << endl;
    auto rpc_rsp = MessageFactory::create<RpcResponse>();
    rpc_rsp->setId("222");
    rpc_rsp->setMType(MType::RSP_TOPIC);
    rpc_rsp->setRCode(RCode::RCODE_OK);
    conn->send(rpc_rsp);
}
int main()
{
    Dispatcher::ptr dispather = make_shared<Dispatcher>();
    dispather->registerHandler<RpcRequest>(MType::REQ_RPC, onRpcRequest);
    dispather->registerHandler<TopicRequest>(MType::REQ_TOPIC, onTopicRequest);

    MessageCallback message_cb = std::bind(&Dispatcher::onMessage, dispather.get(),
                                           placeholders::_1, placeholders::_2);

    BaseServer::ptr server = ServerFactory::create(9090);
    server->setMessageCallback(message_cb);

    server->start();
}
// #include "message.hpp"
// #include "net.hpp"
// using namespace zyb_rpc;
// using namespace std;
// // using ConnectionCallback = std::function<void(const BaseConnection::ptr &)>;
// // using CloseCallback = std::function<void(const BaseConnection::ptr &)>;
// // using MessageCallback = std::function<void(const BaseConnection::ptr &, BaseMessage::ptr &)>;
// void onMessage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg)
// {
//     std::string body = msg->serialize();
//     cout << body << endl;
//     auto rpc_rsp = MessageFactory::create<RpcResponse>();
//     rpc_rsp->setId("111");
//     rpc_rsp->setMType(MType::RSP_RPC);
//     rpc_rsp->setRCode(RCode::RCODE_OK);
//     rpc_rsp->setResult(33);
//     conn->send(rpc_rsp);
// }

// int main()
// {
//     BaseServer::ptr server = ServerFactory::create(9090);
//     server->setMessageCallback(onMessage);
//     server->start();
// }
